<template>
  <div class="app-container">
    <div class="FirstPage">
      <div class="main_part">
        <div class="part_nav dataTong">
          <h2 class="title iconfonta"><i class="iconfont icon-kuaijierukou"></i> 送检动态</h2>
          <div class="contain table">
            <div class="module-table">
              <table>
                <tr>
                  <th width="25%">送样时间</th>
                  <th width="30%">样品名称</th>
                  <th width="15%">样品批号</th>
                  <th width="15%">送样人</th>
                  <th width="15%">送样组</th>
                </tr>
                <tr v-for="(item,index) in sampleTable" :key="index" v-if="index < 5">
                  <td width="25%"><p class="listTime">{{item.createTimeMinFt}}</p></td>
                  <td width="30%"><p class="listName" :title="item.materialName">{{item.materialName}}</p></td>
                  <td width="15%"><p :title="item.sampleNum">{{item.sampleNum}}</p></td>
                  <td width="15">
                    <p v-if="item.userName !='未送样'">{{item.userName}}</p>
                    <p style="color: #ffbb60" v-else>{{item.userName}}</p>
                  </td>
                  <td width="15%"><p>{{item.deptName}}</p></td>
                </tr>
              </table>
            </div>
          </div>
        </div>
        <div class="part_nav tongzhi">
          <h2 class="title iconfonte"><i class="iconfont icon-tongzhi"></i> 通知</h2>
          <div class="contain">
            <transaction-table/>
          </div>
        </div>
        <div class="clearBoth"></div>
      </div>
      <div class="main_part middle_main_part">
        <div class="part_nav paiming">
          <h2 class="title iconfontd"><i class="iconfont icon-tongji4"></i> 本月工时&及时率排名</h2>
          <div class="contain">
            <div class="body-left">
              <div class="icons">
                <img src="@/assets/img/paihang1s.png"/>
                <p class="txt">工作量</p>
                <p class="dw">小时</p>
              </div>
              <ul class="workTable">
                <li v-for="(item,index) in workHourTable" :key="index">
                  <p class="workPart1">{{index+1}}</p>
                  <p class="workPart2">{{item.userName}}</p>
                  <p class="workPart3">{{item.hours}}</p>
                </li>
              </ul>
            </div>
            <!--及时率排行-->
            <div class="body-right">
              <div class="icons">
                <img src="@/assets/img/paihang2s.png"/>
                <p class="txt">及时率</p>
                <p class="dw">%</p>
              </div>
              <ul class="workTable">
                <li v-for="(item,index) in rateTable" :key="index">
                  <p class="workPart1">{{index+1}}</p>
                  <p class="workPart2">{{item.userName}}</p>
                  <p class="workPart3">{{item.effect}}</p>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div class="part_nav banben">
          <h2 class="title iconfontc"><i class="iconfont icon-shezhi"></i> 版本信息</h2>
          <div class="contain">
            <div class="titlen">
              <p>威尔药业</p>
              <p class="subtitle">智慧检验大数据管理系统v3.0</p>
            </div>
            <div class="userTong">
              <div class="nav">
                <i class="iconfont iconfont1 icon-yonghu-yuan"></i>
                <p>总用户数：<span>{{countInfo.userCount}}</span></p>
                <p>今日用户：<span class="green">{{countInfo.seeCount}}</span></p>
              </div>
              <div class="nav">
                <i class="iconfont iconfont2 icon-shijiyanshou"></i>
                <p>今日送检：<span class="green">{{countInfo.sampleCount}}</span></p>
                <p>今日完成：<span class="green">{{countInfo.complete}}</span></p>
              </div>
            </div>
          </div>
        </div>
        <div class="part_nav middle">
          <h2 class="title iconfontb"><i class="iconfont icon-kuaijierukou"></i> 常用功能</h2>
          <div class="contain">
            <div class="dataList" v-for="(item,index) in routerList" :key="index">
              <span class="delete" @click="deleteRoute(item)"><i class="el-icon-remove-outline"></i></span>
              <div class="image" @click="goPage(item.name)">
                <i class="iconfont" :class="item.icon"></i>
              </div>
              <p class="name">{{ item.title }}</p>
            </div>
            <div class="dataList" v-if="routerList.length < 8">
              <div class="image" @click="openList()">
                <i class="iconfont icon-jia4"></i>
              </div>
              <p class="name">添加入口</p>
            </div>
            <div class="clearBoth"></div>
          </div>
        </div>
      </div>
      <div class="main_part last">
        <div class="part_nav baobiao">
          <h2 class="title "><i class="iconfont icon-jianceyangpin"></i> 科室月度送样 <span class="red">（未完成）</span>
            <div class="mouth">
              <span v-for="(item,index) in mothSamples" :key="index" :class="{'active':mouthIndex == index}"
                    @click="checkMouth(index)">{{item.moth}}</span>
            </div>
          </h2>
          <div class="contain">
            <div class="echart" ref="echart1"></div>
          </div>
        </div>
      </div>
    </div>
    <div>
      <el-dialog width="300px" append-to-body title="添加入口"
                 :visible.sync="dialogVisible"
                 :before-close="closeDialog"
      >
        <div class="csstop">
          <div class="cssborder"></div>
          <div class="cssborder2"></div>
          <div class="cssborder3"></div>
        </div>
        <div class="zll_checkboxG">
          <el-checkbox-group class="check_group" v-model="checkRouterList">
            <el-checkbox v-for="(item,index) in routerListAll" :key="index" :label="item.name">{{item.meta.title}}
            </el-checkbox>
          </el-checkbox-group>
        </div>

        <div slot="footer" class="dialog-footer" style="margin-top:40px">
          <el-button type="primary" @click="submitFun()"
                     size="mini" class="zll_dialog_bt"
          >
            提 交
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import TransactionTable from '../notice/components/TransactionTable'
  import echartOption from './echart'
  import {hasPermission} from "@/utils/hasPermission";
  import {formatDate} from '@/utils/formatDate'
  import {sortS} from '@/utils/common'

  export default {
    data() {
      return {
        dialogVisible: false,

        countInfo: {
          userCount: 0,
          sampleCount: 0,
          seeCount: 0,
          complete: 518,
        },
        sampleTable: [],

        routerListAll: [],
        routerList: [],
        checkRouterList: [],
        mouthIndex: 0,
        workHourTable: [],
        rateTable: [],

        //月度送样
        mothSamples: [],
      };
    },
    methods: {

      deleteRoute(item) {
        let self = this;
        self.$confirm('确定删除该快捷键？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          self.$http({
            url: "/drug/router/deleteUserRouter",
            method: "post",
            params: {id: item.id}
          }).then(resp => {
            if (resp.success) {
              self.getRouterInfo();
              self.$notify({
                title: '提示',
                message: "删除成功！",
                type: 'success'
              });
              return
            }
            self.$notify({
              title: '提示',
              message: "操作失败，请联系管理员！",
              type: 'error'
            });
          });
        });
      },

      getAllRouters() {
        let routers = this.$store.getters.permission_routes;
        let routersInfo = [];
        this.iterateTree(routers, routersInfo);
        this.routerListAll = routersInfo;
      },
      iterateTree(routers, routersInfo) {
        for (let data of routers) {
          if (data.choose && hasPermission(data.meta.permission)) {
            data.icon = data.meta.iconNew;
            routersInfo.push(data);
          }
          if (data.children) {
            this.iterateTree(data.children, routersInfo);
          }
        }
      },

      openList() {
        this.dialogVisible = true;
      },
      submitFun() {
        let self = this;
        let updateRoute = [];
        if (self.checkRouterList.length > 8) {
          self.$notify({
            title: '提示',
            message: "快捷键少于8个！",
            type: 'warning'
          });
          return;
        }
        for (let value of self.checkRouterList) {
          let choose = self.routerListAll.find((item) => item.name == value);
          if (choose) {
            let obj = {};
            obj.name = choose.name;
            obj.title = choose.meta.title;
            obj.icon = choose.icon;
            updateRoute.push(obj);
          }
        }
        let param = {userId: self.$store.getters.userId, userRouters: updateRoute};
        self.$http({
          url: "/drug/router/addUserRouter",
          method: "post",
          data: JSON.stringify(param),
          dataType: 'json',
          contentType: "application/json",
        }).then(resp => {
          self.$notify({
            title: '提示',
            message: "更新快捷窗口成功！",
            type: 'success'
          });
          self.getRouterInfo();
          self.closeDialog();
        });

      },
      closeDialog() {
        this.dialogVisible = false;
      },
      goPage(name) {
        this.$router.push({name})
      },

      barActive() {//自动高亮
        let echart = this.$echarts.init(this.$refs.echart1);
        let index = -1; //高亮所在下标
        let dataLength = echartOption.option3.series[0].data.length;
        setInterval(() => { // 清除之前的高亮
          echart.dispatchAction({
            type: 'downplay',
            seriesIndex: 0,
            dataIndex: index
          });
          index = (index + 1) % dataLength; // 当前下标高亮
          echart.dispatchAction({
            type: 'highlight',
            seriesIndex: 0,
            dataIndex: index
          });
          echart.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            dataIndex: index
          });
          if (index > dataLength) {
            index = 0
          }
        }, 1500)
      },

      checkMouth(index) {
        let self = this;
        this.mouthIndex = index;
        let datas = this.mothSamples[index];
        let echart1 = this.$echarts.init(this.$refs.echart1);
        let option = echartOption.option3;
        option.xAxis[0].data = [];
        option.series[0].data = [];
        option.series[1].data = [];
        let max = 1;
        for (let i = 0; i < datas.counts.length; i++) {
          max = max > datas.counts[i] ? max : datas.counts[i];
        }
        let topShow = max * 0.2;
        for (let i = 0; i < datas.counts.length; i++) {
          option.xAxis[0].data.push(datas.deptNames[i]);
          option.series[0].data.push(datas.counts[i]);
          option.series[1].data.push(datas.counts[i] + topShow)
        }
        option.series[1].label.normal = {
          show: true,
          position: "top",
          distance: 1,
          formatter: function (params) {
            let dataIndex = params.dataIndex;
            let val = datas.uncount[dataIndex]
            return "（" + val + "）"
          },
          color: '#ff4949'
        };
        echart1.setOption(option)
      },

      sortByDept(arrays, orderDeptIds) {
        let sorts = [];
        if (orderDeptIds.length > 0) {
          for (let deptId of orderDeptIds) {
            let index = arrays.findIndex(item => (item.id == deptId || item.deptId == deptId));
            if(index > -1){
              sorts.push(arrays[index]);
              arrays.splice(index,1);
            }
          }
        }
        return sorts;
      },

      getMothTotal() {
        let self = this;
        this.$http({
          url: "/drug/bigScreen/queryMothTotal",
          method: "post",
        }).then(resp => {
          let mothSet = new Set();
          let mothMap = {};
          let orderDeptIds = [];
          if (resp.result.length > 0) {
            orderDeptIds = resp.result[0].deptIds;
          }
          for (let data of resp.result) {
            mothSet.add(data["startTime"]);
            if (mothMap[data["startTime"]]) {
              mothMap[data["startTime"]].push(data)
            } else {
              mothMap[data["startTime"]] = [data];
            }
          }
          let mothList = sortS(Array.from(mothSet), true);
          self.mothSamples = [];
          for (let i = 0; i < mothList.length; i++) {
            let key = mothList[i];
            let m = key.split("-")[1] + '月';
            let mothData = {moth: m, deptNames: [], counts: [], uncount: []};
            let md = self.sortByDept(mothMap[key],orderDeptIds);
            for (let dt of md) {
              mothData.deptNames.push(dt.deptName);
              mothData.counts.push(dt.counts);
              mothData.uncount.push(dt.unCounts);
            }
            self.mothSamples.push(mothData);
          }
          let echart1 = this.$echarts.init(this.$refs.echart1);
          let option = echartOption.option3;
          console.log('----queryMothTotal-----');
          console.log(self.mothSamples);
          option.xAxis[0].data = [];
          option.series[0].data = [];
          option.series[1].data = [];
          let max = 1;
          for (let i = 0; i < self.mothSamples[0].counts.length; i++) {
            max = max > self.mothSamples[0].counts[i] ? max : self.mothSamples[0].counts[i];
          }
          let topShow = max * 0.2;
          for (let i = 0; i < self.mothSamples[0].counts.length; i++) {
            option.xAxis[0].data.push(self.mothSamples[0].deptNames[i]);
            option.series[0].data.push(self.mothSamples[0].counts[i]);
            option.series[1].data.push(self.mothSamples[0].counts[i] + topShow)
          }
          option.series[1].label.normal = {
            show: true,
            position: "top",
            distance: 1,
            formatter: function (params) {
              let dataIndex = params.dataIndex;
              let val = self.mothSamples[0].uncount[dataIndex]
              return "（" + val + "）"
            },
            color: '#ff4949'
          };
          echart1.setOption(option)
        });
      },


      getBigScreenSampleList() {
        let self = this;
        this.$http({
          url: "/drug/bigScreen/querySampleBigScreenList",
          method: "post",
        }).then(resp => {
          self.sampleTable = resp.result;
        });
      },

      getRouterInfo() {
        let self = this;
        self.$http({
          url: "/drug/router/queryUserRouterList",
          method: "post",
          params: {userId: self.$store.getters.userId}
        }).then(resp => {
          if (resp.success) {
            self.routerList = resp.result;
            for (let data of self.routerList) {
              self.checkRouterList.push(data.name)
            }
          }
        });
      },

      getSysCountInfo() {
        let self = this;
        self.$http({
          url: "/drug/queryAllLoginList",
          method: "post",
        }).then(resp => {
          if (resp.success) {
            self.countInfo.userCount = resp.result.length;
          }
        });
        self.$http({
          url: "/drug/loginLog/queryLoginLogCount",
          method: "post",
        }).then(resp => {
          if (resp.success) {
            self.countInfo.seeCount = resp.result;
          }
        });
        self.$http({
          url: "/drug/sample/querySampleAllCount",
          method: "post",
        }).then(resp => {
          if (resp.success) {
            self.countInfo.sampleCount = resp.result.total;
            self.countInfo.complete = resp.result.complete;
          }
        });
      },
      getWorkHour() {
        let self = this;
        let year = formatDate(new Date(), "yyyy");
        let moth = formatDate(new Date(), "MM");
        let day = year + "-" + moth + "-01";
        let endDay = year + "-" + moth + "-31";
        this.$http({
          url: "/drug/bigScreen/queryWorkHour",
          method: "post",
          params: {startTime: day, endTime: endDay}
        }).then(resp => {
          self.workHourTable = resp.result;
        });
      },
      getMothRate() {
        let self = this;
        let year = formatDate(new Date(), "yyyy");
        let moth = formatDate(new Date(), "MM");
        let day = year + "-" + moth + "-01";
        let endDay = year + "-" + moth + "-31";
        this.$http({
          url: "/drug/bigScreen/queryMothRate",
          method: "post",
          params: {startTime: day, endTime: endDay}
        }).then(resp => {
          self.rateTable = resp.result;
        });
      },
    },
    mounted() {
      this.getAllRouters();
      this.getRouterInfo();
      this.getSysCountInfo();
      this.getMothTotal();
      this.barActive();
      this.getBigScreenSampleList();
      this.getWorkHour();
      this.getMothRate();
    },
    components: {TransactionTable},
  };
</script>
<style scoped lang="scss">
  @import './index.scss';
</style>
